/***********************************************************************************
Copy right:	    Coffee Tech.
Author:         jiaoyue
Date:           2022-03-23
Description:    console模块
***********************************************************************************/

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdarg.h>

#include "log_console.h"

static int console_fd = -1;

/**
 * @brief 初始化log_console
 * @return 0 -1
 */
int log_console_init()
{
    console_fd = open(LOG_CONSOLE, O_WRONLY);
    if (console_fd < 0)
    {
        printf("open %s error\n", LOG_CONSOLE);
        return -1;
    }

	return 0;
}

static ssize_t log_console_write(const void *buf, size_t count)
{
    int ret = write(console_fd, buf, count);
    if(ret < 0)
    {
        perror("write err");
    }
}

#define MAX_LOG_BUF_LEN (20*1024)  //打印内容不能超过这个

int log_console(const char *format, ...)
{
    char str_tmp[MAX_LOG_BUF_LEN];
    va_list arg;
    int len;

    va_start(arg, format);
    len = vsnprintf(str_tmp, MAX_LOG_BUF_LEN, format, arg);
    va_end(arg);
    str_tmp[len] = '\0';

    return log_console_write(str_tmp, strlen(str_tmp));
}
